package com.sxdx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxdx.common.Result;
import com.sxdx.convert.BookConvert;
import com.sxdx.convert.DtoToEntityConverter;
import com.sxdx.entity.Book;
import com.sxdx.entity.dto.BookDto;
import com.sxdx.mapper.BookMapper;
import com.sxdx.service.IBookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxdx.utils.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 靳杰
 * @since 2023-12-22
 */
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements IBookService {
    @Autowired
    private BookMapper bookMapper;

    @Override
    public Result selectBookDetailById(Book book) {
        Book bookDetail = bookMapper.selectBookDetailById(book);
        return Result.success(bookDetail);
    }

    @Override
    public Result<?> addBook(BookDto bookDto) {
        try{
//            Book book = BookConvert.convert.fromDto(bookDto);
            Book book = DtoToEntityConverter.convertDtoToEntity(bookDto, Book.class);
            String uuid = UuidUtil.get32UUID();
            bookDto.setUuid(uuid);
            int count = bookMapper.insert(book);
            if (count!=0)
                return Result.success("成功增加图书");
            else
                return Result.error("增加图书失败");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Result<?> deleteBook(String uuid) {
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Book::getUuid,uuid);
        int count = bookMapper.delete(wrapper);
        return (count==0) ? Result.error("删除失败") :Result.success("删除成功");
    }

    @Override
    public Result<?> updateBook(BookDto bookDto) {
        Book book = DtoToEntityConverter.convertDtoToEntity(bookDto, Book.class);
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Book::getUuid,book.getUuid());
        int count = bookMapper.update(book, wrapper);
        return (count==0) ? Result.error("更新失败"):Result.success("更新成功");
    }

    @Override
    public Result<?> searchBook(Integer currentPage,Integer pageSize,String searchByName) {
        Page<Book> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Book> like = wrapper.like(Book::getName, searchByName);
        Page<Book> bookPage = bookMapper.selectPage(page, like);
        return (bookPage != null) ? Result.success(bookPage) : Result.error("图书查询失败");

    }
}